/**
 * @file 工单操作-多工程师分润
 * @author sunlife <1298629573@qq.com>
 * @date 2021-07-21 20:13:16
 */
layui.define(['layer', 'form', 'laytpl', '$http', 'table', 'NP', 'zmnUtils'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var laytpl = layui.laytpl;
    var opCommonUtils = layui.list_modify_common;
    var table = layui.table;
    var NP = layui.NP;
    var zmnUtils = layui.zmnUtils;

    var $http = layui.$http;

    let SAVE_MASTERSHARING_URL = "/work/modify/save/mastersharing.action";


    var templeteFormatter = {
        masterTypeTempleteFunc: function (d) {
            return d.type == 1 ? '主' : '从';
        },
        masterNameTempleteFunc: function (d) {
            return d.masterName + '-' + d.identityName;
        },
        masterIdTempleteFunc: function (d) {
            return '<div><span class="master" id="' + d.masterId + '"></span></div>';
        },
       shareRateTempleteFunc: function (d) {
            let sharingHtml = '<input class="layui-input shareRate" type="text" name="master-shareRate-' + d.masterId +
                '" autocomplete="off" placeholder="请输入0~100的数字" lay-filter="master-sharing"';
            if (d.shareRate !== null) {
                sharingHtml = sharingHtml + ' value="'+ changeTwoDecimal(NP.divide(d.shareRate, 100)) +'"';
            }
            sharingHtml = sharingHtml + '>';

            return sharingHtml;
        }
    };

    var cols = [
        [
            {field: 'masterId', hide: true},
            {field: 'type', hide: true},
            {field:'typeName', title:'类型', width:50, align:'center', templet: templeteFormatter.masterTypeTempleteFunc },
            {field:'masterNameFunc', title:'工程师姓名', align:'center', templet: templeteFormatter.masterNameTempleteFunc },
            {field:'sharing', title:'分润比例', templet: templeteFormatter.shareRateTempleteFunc}
        ]
    ];

    /**
     * 判断是否是正整数
     * @param val {number/string} 字符串或数字
     * @returns {boolean} 返回是否是数字
     */
    function isNumber(val) {
        var reg = new RegExp(/^[0-9]+([.]{1}[0-9]{1,2})?$/);//正整数
        return reg.test(val);
    }
    
    function changeTwoDecimal(val) {
        if (!val) {
            return ""
        }
        let f_x = parseFloat(val);
        f_x = Math.round(val * 100) / 100;
        let s_x = f_x.toString();
        let pos_decimal = s_x.indexOf('.');
        if (pos_decimal < 0) {
            pos_decimal = s_x.length;
            s_x += '.';
        }
        while (s_x.length <= pos_decimal + 2) {
            s_x += '0';
        }
        return s_x;
    }

    /**
     * 获取某个元素下子元素的文本值
     * @param item
     * @param ele
     * @returns {jQuery}
     */
    function getText(item, ele) {
        return $(item).find(ele).text() || $(item).find(ele).val();
    }

    /**
     * 获取工程师算账列表;
     */
    function getMasterSharingList() {
        let $tr = $('.masterdetail tbody').find('tr');
        let arr = [];
        $tr.each(function (i, item) {
            let temp = {
                masterId: getText(item, 'td[data-field=masterId]'),
                masterName: getText(item, 'td[data-field=masterNameFunc]'),
                type: getText(item, 'td[data-field=type]')
            };

            // 多师傅提成数据
            let masterId = getText(item, 'td[data-field=masterId]');
            temp.shareRate = NP.times(getText(".masterdetail", 'input[name=master-shareRate-' + masterId + ']') || 0, 100);

            arr.push(temp);

        });
        return arr;
    }

    /**
     * 提示消息
     * @param str {string} 提示信息
     * @returns {*}
     */
    function toast(opt) {
        layer.msg(opt.title, {
            icon: opt.icon,
            time: opt.time || 1000,
        }, function () {
            if (opt.icon == 1) {
                opCommonUtils.goOperateHome();
                //    location.reload();
            }
        })
    };

    let tips = function (ele, str, clearOldValue, callback) {
        toast({
            title: str,
            icon: 2,
            time: 2000
        });
        $(ele).focus();
        if (clearOldValue) {
            $(ele).val('');
        }
        if (typeof callback === 'function') {
            callback();
        }
        return false;
    };

    /**
     * 校验数据
     */
    function verifyMasterSharing(masterSharingList) {
        let totalShare = 0;
        for (let i = 0; i < masterSharingList.length; i++) {
            totalShare += parseInt(masterSharingList[i].shareRate);
        }
        if (totalShare !== 10000) {
            tips($(".shareRate"), "工程师分润总和不等于100", false);
            return false;
        }
        return true;

    }

    /**
     * 初始化页面
     */
    function initPage() {
        //配件明细
        table.render({
            elem: '#masterdetail',
            cols: cols,
            data: masterList,
            width: 400
        });
    }

    function save (data, btn) {
        return $http.lockSave(SAVE_MASTERSHARING_URL, data, btn);
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        $('.masterdetail').on('blur', '.shareRate', function (event) {
            let val = event.currentTarget.value;
            if(val===''){
                return;
            }
            if(val > 100){
                tips(this, '不能大于100', true);
                return;
            }
            if(val < 0){
                tips(this, '不能小于0', true);
                return;
            }
            if(!isNumber(val)){
                tips(this, '请输入正数且最多两位小数', true);
                return;
            }
            $(this).val(changeTwoDecimal(val));
        });
        // $('.masterdetail').on('keyup', '.shareRate', function (event) {
        //     let val = event.currentTarget.value;
        //     if(val===''){
        //         return;
        //     }
        //     if (val.length > 1) {
        //         val = val.replace(/\b(0+)/gi,"");
        //         $(this).val(val);
        //     }
        //     if(val > 100){
        //         tips(this, '不能大于100', true);
        //     }
        //     if(val < 0){
        //         tips(this, '不能小于0', true);
        //     }
        //     if(!isNumber(val)){
        //         tips(this, '请输入正数且最多两位小数', true);
        //     }
        // });

        form.on('submit(save)', function (obj) {
            console.log(obj);
            let field = obj.field;
            // 获取数据
            let masterSharingList = getMasterSharingList();
            // 校验数据
            let result = verifyMasterSharing(masterSharingList);
            if (!result) {
                return false;
            }

            let params = {
                orderId: field.orderId,
                workId: field.workId,
                sharingInfoList: masterSharingList
            };


            // 提交
            var $btns = $(obj.elem).parent().children();
            save(params, $btns).then(function (result) {
                zmnUtils.layui.toastSuccess('操作成功', function () {
                    opCommonUtils.goOperateHome();
                });
            }, function (msg) {
                var reason = msg || '未知';
                zmnUtils.layui.toastError('保存工程师分润失败，原因：' + reason);
            });
        });

        //取消
        form.on('submit(cancel)', function (data) {
            opCommonUtils.goOperateHome();
            return false
        });

    }

    // 程序入口
    function init() {

        // 初始化页面
        initPage();

        // 初始化事件
        initEvent();

    }


    // 初始化
    init();

    exports('oms_work_modify_mastersharing');
});
